/*******************************************************************************
 *    系统名称   : 约汗乐动力接口/后台管理系统
 *    客户             : 约汗乐动力
 *    文件名        ： StringEscapeEditor.java
 *              (C) Copyright 博智乐创 Corporation 2015
 *               All Rights Reserved.
 *              http://www.bozlc.com
 * *****************************************************************************
 *    注意： 本内容仅限于约汗乐动力软件公司内部使用，未经许可禁止转发
 ******************************************************************************/
package com.xiake.utils;

import java.beans.PropertyEditorSupport;

import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.web.util.HtmlUtils;
import org.springframework.web.util.JavaScriptUtils;

// TODO: Auto-generated Javadoc
/**
 * 与spring mvc的@InitBinder结合
 * 
 * 用于防止XSS攻击和防止sql攻击.
 */
public class StringEscapeEditor extends PropertyEditorSupport {

	/** The escape html. */
	private boolean escapeHTML;// 编码HTML
	
	/** The escape java script. */
	private boolean escapeJavaScript;// 编码javascript
	
	/** The escape sql. */
	private boolean escapeSQL;  //编码sql

	/**
	 * Instantiates a new string escape editor.
	 */
	public StringEscapeEditor() {
		super();
	}

	/**
	 * Instantiates a new string escape editor.
	 *
	 * @param escapeHTML the escape html
	 * @param escapeJavaScript the escape java script
	 * @param escapeSQL the escape sql
	 */
	public StringEscapeEditor(boolean escapeHTML, boolean escapeJavaScript,boolean escapeSQL) {
		super();
		this.escapeHTML = escapeHTML;
		this.escapeJavaScript = escapeJavaScript;
		this.escapeSQL = escapeSQL;
	}

	/* (non-Javadoc)
	 * @see java.beans.PropertyEditorSupport#getAsText()
	 */
	@Override
	public String getAsText() {
		Object value = getValue();
		return value != null ? value.toString() : "";
	}

	/* (non-Javadoc)
	 * @see java.beans.PropertyEditorSupport#setAsText(java.lang.String)
	 */
	@Override
	public void setAsText(String text) throws IllegalArgumentException {
		if (text == null) {
			setValue(null);
		} else {
			String value = text;
			if (escapeHTML) {
				value = HtmlUtils.htmlEscape(value);
			}
			if (escapeJavaScript) {
				value = JavaScriptUtils.javaScriptEscape(value);
			}
			if (escapeSQL) { 
				value = StringEscapeUtils.escapeSql(value);
			}
			setValue(value);
		}
	}

}
